<?php

namespace Ignus\View\TokenParser;

use Ignus\View\TokenParser;
use Ignus\View\Node\ForNode;
use Ignus\View\Node\Expression\AssignName;
use Ignus\View\Token;

class ForParser extends TokenParser
{
    public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $targets = $this->parser->getExpressionParser()->parseAssignmentExpression();
        $this->parser->getStream()->expect(Token::OPERATOR_TYPE, 'in');
        $seq = $this->parser->getExpressionParser()->parseExpression();

        $ifexpr = null;
        if ($this->parser->getStream()->test(Token::NAME_TYPE, 'if')) {
            $this->parser->getStream()->next();
            $ifexpr = $this->parser->getExpressionParser()->parseExpression();
        }

        $this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse(array($this, 'decideForFork'));
        if ($this->parser->getStream()->next()->getValue() == 'else') {
            $this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
            $else = $this->parser->subparse(array($this, 'decideForEnd'), true);
        } else {
            $else = null;
        }
        $this->parser->getStream()->expect(Token::BLOCK_END_TYPE);

        if (count($targets) > 1) {
            $keyTarget = $targets->getNode(0);
            $keyTarget = new AssignName($keyTarget->getAttribute('name'), $keyTarget->getLine());
            $valueTarget = $targets->getNode(1);
            $valueTarget = new AssignName($valueTarget->getAttribute('name'), $valueTarget->getLine());
        }
        else {
            $keyTarget = new AssignName('_key', $lineno);
            $valueTarget = $targets->getNode(0);
            $valueTarget = new AssignName($valueTarget->getAttribute('name'), $valueTarget->getLine());
        }

        return new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, $lineno, $this->getTag());
    }

    public function decideForFork(Token $token)
    {
        return $token->test(array('else', 'endfor'));
    }

    public function decideForEnd(Token $token)
    {
        return $token->test('endfor');
    }

    public function getTag()
    {
        return 'for';
    }
}
